import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;

import java.io.*;

public class FormatJava {

  private static void close(Closeable closeable) {
    try {
      if (closeable != null) {
        closeable.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static String fileToString(File file) {
    InputStream is = null;
    try {
      is = new FileInputStream(file);
      ByteArrayOutputStream bos = new ByteArrayOutputStream(is.available());
      byte[] buffer = new byte[2048];
      int len = -1;
      while ((len = is.read(buffer)) > 0) {
        bos.write(buffer, 0, len);
      }
      return new String(bos.toByteArray());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      close(is);
    }
    return null;
  }

  private static void stringToFile(String content, File file) {
    OutputStream os = null;
    try {
      os = new FileOutputStream(file);
      os.write(content.getBytes());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      close(os);
    }
  }

  private static void formatterFolder(File folder) {
    if (folder.isFile()) {
      return;
    }
    File[] files = folder.listFiles();
    for (File file:files) {
      if (file.isDirectory()) {
        formatterFolder(file);
      } else {
        String content = fileToString(file);
        try {
          System.out.println("content:" + content);
          content = new Formatter().formatSource(content);
        } catch (FormatterException e) {
          e.printStackTrace();
        }
        stringToFile(content, file);
      }
    }
  }

  public static void main(String[] args) {
//    if (args.length < 2) {
//      System.out.println("please input root folder");
//      return;
//    }
//    System.out.println("args:" + args[2]);
    formatterFolder(new File("/Users/zhangqianchu/OpenGL/works/WifiLocation/app/src/main/java/"));
  }
}
